import os

import PyPDF2
from PyPDF2 import PdfMerger

def count_pdf_pages(pdf_file):
    with open(pdf_file, 'rb') as file:
        pdf_reader = PyPDF2.PdfReader(file)
        page_count = len(pdf_reader.pages)
    return page_count

if __name__ == '__main__':
    blank_page = PyPDF2.PdfReader(open('blank.pdf', 'rb'))
    target_path = r'/Users/edmond/Downloads/期末成绩单季分析表'  # pdf目录文件

    path = __file__
    # target_path = os.path.dirname(path)
    pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]
    pdf_lst = [os.path.join(target_path, filename) for filename in pdf_lst]

    file_merger = PdfMerger()
    for pdf in pdf_lst:
        print(pdf)
        file_merger.append(pdf, import_outline=False)  # 合并pdf文件
        if count_pdf_pages(pdf) % 2 != 0:
            file_merger.append(blank_page, import_outline=False)

    file_merger.write(r"/Users/edmond/Downloads/期末成绩单季分析表/成绩单等.pdf")